import type { ZkbzAddEmits, ZkbzAddProps } from "./prop"
import { addZkpBzList, getZkpBzList, MAGIC_SUCC_CODE } from "@api"
import { uuid } from "@ui/utils/win"
import type { SetupContext } from "vue"
import { zkspZdObj } from "@utils/dic"
export function use(props: ZkbzAddProps, emit: SetupContext<ZkbzAddEmits>['emit']) {
  const currentRow = ref(),
    tableData = ref<LisZkpBzItem[]>([]),
    formTable = ref()
  watch(() => props.data, query, { immediate: true })
  function query() {
    const { id, yqid, zkpid } = props.data
    if (id) {
      getZkpBzList({ xmid: id, yqid, zkpid }).then(({ data: { list } }) => {
        tableData.value = list.map(it => {
          it.zkspdm_mc = zkspZdObj[it.zkspdm]
          return it
        })
      })
    } else {
      tableData.value = []
    }
  }
  function setFormData(data: any) {
    tableData.value = data
    nextTick(() => {
      if (formTable.value) {
        formTable.value.layout()
      }
    })
  }
  function add() {
    const data = props.data
    tableData.value.push({ ...data, id: uuid(), fs: 1 } as LisZkpBzItem)
  }
  function del() {
    const obj = currentRow.value
    if (obj) {
      const { id } = obj
      setFormData(tableData.value.filter(it => it.id != id))
    } else {
      ElMessage({ type: 'warning', message: '请选择要删除的项目' })
    }
  }
  function save() {
    const { yqid, id, zkpid } = props.data
    addZkpBzList({ data: tableData.value, yqid, xmid: id, zkpid }).then(({ code, data, message }) => {
      if (code === MAGIC_SUCC_CODE) {
        ElMessage({ type: 'success', message: '保存成功' })
        query()
      } else
        ElMessage({ type: 'warning', message })
    })
  }
  return { tableData, add, formTable, save, del, currentRow, query }
}